<template>
  <div
    :class="[disabled ? 'is_disabled' : 'is_valid']"
    class="xh-files-cont">
    <el-upload
      ref="fileUpload"
      :action="crmFileSaveUrl"
      :headers="httpHeader"
      :on-preview="handleFilePreview"
      :before-remove="deleteFile"
      :on-success="imgFileUploadSuccess"
      :on-exceed="handleExceed"
      :limit="fileLimit"
      multiple
      :file-list="showFileLIst"
      :data="{batchId: batchId}">
      <flexbox
        :class="[disabled ? 'is_disabled' : 'is_valid']"
        class="f-header">
        <div class="f-name"><i class="el-icon-paperclip"></i>附件</div>
      </flexbox>
    </el-upload>
  </div>
</template>
<script type="text/javascript">
import arrayMixin from './arrayMixin'
import { crmFileSave, crmFileDelete, crmFileSaveUrl } from '@/api/common'
import { fileSize } from '@/utils/index'
import axios from 'axios'
import {
  guid
} from '@/utils'
export default {
  name: 'XhFiles', // 新建 file  以数组的形式上传
  components: {},
  mixins: [arrayMixin],
  props: {
    fileLimit: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      batchId: guid(), // 批次ID
      uploadFileList: []
    }
  },
  computed: {
    crmFileSaveUrl() {
      return crmFileSaveUrl
    },
    httpHeader() {
      return {
        'Admin-Token': axios.defaults.headers['Admin-Token']
      }
    }
  },
  watch: {
    showFileLIst(newValue){
      let files = [];
      if(newValue.length){
        this.batchId = newValue[0].response ? newValue[0].response.batchId : newValue[0].batchId;
        for(let i=0;i<newValue.length;i++){
          if(newValue[i].response){
            files.push(newValue[i].response);
          }else{
            files.push(newValue[i]);
          }
        }
      }
      this.uploadFileList = files;
    },
    uploadFileList(newValue){

      for(let i=0; i < newValue.length;i++){
        newValue[i].size = fileSize(newValue[i].size);
      }
      this.$emit('value-change', {
        index: this.index,
        batchId: this.batchId,
        value: newValue
      })
    }
  },
  mounted() {},
  methods: {

    // 上传文件
    imgFileUploadSuccess(response, file, fileList) {
      // response.size = fileSize(response.size)
      this.showFileLIst = fileList;
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前只限上传 ${this.fileLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 查看文件
    handleFilePreview(file) {
      if (!this.isView(file)) {
        this.$message({
          message: '该文件不可预览',
          type: 'warning'
        })
        return
      }
      if (file.response || file.fileId) {
        let perviewFile
        if (file.response) {
          perviewFile = file.response
        } else {
          perviewFile = {
            url: file.filePath,
            name: file.name
          }
        }
        this.$bus.emit('preview-image-bus', {
          index: 0,
          data: [perviewFile]
        })
      }
    },
    // 只有图片可以预览
    isView(file) {
      // 文件路径
      var filePath = file.filePath ? file.filePath : file.response.url
      // 获取最后一个.的位置
      var index = filePath.lastIndexOf('.')
      // 获取后缀
      var ext = filePath.substr(index + 1)
      // 输出结果
      return this.isAssetTypeAnImage(ext)
    },
    isAssetTypeAnImage(ext) {
      return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1
    },
    /** 删除图片 */
    deleteFile(file, fileList) {
      return this.$confirm(`您确定要删除 ${file.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
        .then(() => {
          crmFileDelete({
            id: file.response ? file.response.fileId : file.fileId
          })
            .then(res => {
              this.showFileLIst = fileList.map(file => {return file.response ? file.response : file});
              this.$message.success('操作成功')
            })
            .catch(() => {})
        })
    }
  }
}
</script>
<style lang="scss" scoped>
/** 附件  */
.xh-files-cont {
  position: relative;
  display: inline-block;
  border-radius: 3px;
  width: 100%;
  border: 1px solid #ddd;
  padding: 3.5px 5px;
  margin: 3px;
  line-height: 15px;
  /deep/.el-upload--text {
    width: 100%
  }
}

.xh-files-cont.is_disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;
  .f-name {
    background-color: #f0f4f8ea;
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.xh-files-cont.is_valid:hover {
  border-color: #c0c4cc;
}

.f-header {
  cursor: pointer;
  padding: 5px 0 5px;
  .f-logo {
    position: block;
    width: 15px;
    height: 15px;
    margin-right: 8px;
  }
  .f-name {
    color: #3e84e9;
    font-size: 12px;
  }
}
.f-header.is_disabled {
  cursor: not-allowed;
}

.f-body {
  .f-item {
    padding: 3px 0;
    height: 25px;
    .f-img {
      position: block;
      width: 15px;
      height: 15px;
      padding: 0 1px;
      margin-right: 8px;
    }
    .f-name {
      color: #666;
      font-size: 12px;
    }
    .close-button {
      cursor: pointer;
    }
  }
}

.bar-iput {
  position: absolute;
  top: 0;
  left: 0;
  height: 0;
  width: 0;
  opacity: 0;
}
</style>
